#!/usr/bin/env node

const { Command } = require('commander');
const program = new Command();
const fs = require('fs')
program.version('0.0.1', '-v, --version');

program
    .command('create-report')
    .description('create new lesson data')
    .option('-f,--file <filename>', 'file name')
    .action((opts) => {
        initLesson(opts.file)
    })

program
    .command('create-lesson')
    .description('create new lesson data')
    .option('-f,--file <filename>', 'file name')
    .action((opts) => {
        initLesson(opts.file)
    })

program
    .command('add-char')
    .description('add character to lesson')
    .option('-f,--file <filename>', 'file name')
    .action((opts) => {
        addChar(opts.file)
    })

program
    .command('add-word')
    .description('add word to lesson')
    .option('-f,--file <filename>', 'file name')
    .action((opts) => {
        addWord(opts.file)
    })

program
    .command('learn')
    .description('learn words')
    .option('', 'words')
    .action(learnWords)

program.parse(process.argv);

function initLesson(filename) {
    const data = {
        "title": "",
        "write": {
            "characters": [
            ],
            "words": [
            ]
        }
    }

    writeToJson(data)
}

function addChar(filename) {
    if (!fs.existsSync(`./${filename}.json`)) {
        throw Error(`${filename} doesn't exist`)
    }

    const data = require(`./${filename}.json`)

    const readline = require('readline');

    const rl = readline.createInterface({
        input: process.stdin,
        output: process.stdout
    });

    prompt()

    function prompt() {
        rl.question('add char:', (char) => {
            if (data.write.characters.indexOf(char) === -1) {
                data.write.characters.push(char)
            }
            console.log(data.write.characters)
            writeToJson(data, filename)
            prompt();
        });

    }
}

function addWord(filename) {
    if (!fs.existsSync(`./${filename}.json`)) {
        throw Error(`${filename} doesn't exist`)
    }

    const data = require(`./${filename}.json`)

    const readline = require('readline');

    const rl = readline.createInterface({
        input: process.stdin,
        output: process.stdout
    });

    prompt()

    function prompt() {
        rl.question('add word:', (char) => {
            if (data.write.words.indexOf(char) === -1) {
                data.write.words.push(char)
            }
            console.log(data.write.words)
            writeToJson(data, filename)
            prompt();
        });

    }
}

function writeToJson(data, filename) {
    const content = JSON.stringify(data, '', 4)

    fs.writeFile(`./${filename}.json`, content, function (err) {
        if (err) {
            return console.log(err)
        }
    })
}

function learnWords(opts) {

}